package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberEntity;
import com.atguigu.gulimall.seckill.feign.CouponFeign;
import com.atguigu.gulimall.seckill.feign.ProductFeign;
import com.atguigu.gulimall.seckill.interceptor.SeckillInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.vo.SeckillRedisVo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionTo;
import com.atguigu.gulimall.seckill.vo.SkuInfoEntity;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeign couponFeign;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String SECKILL_SESSION = "seckill:sessionMessage:";

    public static final String SECKILL_SESSION_RELATION = "seckill_session_relation";
    //getSemaphore
    public static final String SECKILL_SKU_COUNT_SEMAPHORE = "seckill_semaphore:";

    @Override
    public void up3DaysSeckillProduct() {
        //远程查询出三天内的秒杀场次及关联商品
        R r = couponFeign.get3DaysSeckillPromotion();
        if (r.getCode() == 0) {
            List<SeckillSessionTo> seckillSessionTos = r.getData("data", new TypeReference<List<SeckillSessionTo>>() {});
            if(seckillSessionTos!=null){
                //上架场次信息
                upSeckillSession(seckillSessionTos);
                //上架商品信息
                upSeckillSessionAndSkuInfo(seckillSessionTos);
            }
        }


    }
    public List<SeckillRedisVo> getCurrentSeckillSkusSentinelResource(BlockException e){
        log.info("getCurrentSeckillSkusSentinelResource方法执行");
        return null;
    }
    @Override
    @SentinelResource(value = "getCurrentSeckillSkusSentinelResource",blockHandler = "getCurrentSeckillSkusSentinelResource")
    public List<SeckillRedisVo> getCurrentSeckillSkus() {
        Set<String> keys = stringRedisTemplate.keys(SECKILL_SESSION + "*");
        if(keys!=null){
            long currentTimeMillis = System.currentTimeMillis();
            for (String key : keys) {
                String replace = key.replace(SECKILL_SESSION, "");
                String[] s = replace.split("_");
                long startTime = Long.parseLong(s[0]);
                long endTime = Long.parseLong(s[1]);
                //如果当前场次正在进行中
                if(currentTimeMillis>=startTime && currentTimeMillis<=endTime){
                    List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_SESSION_RELATION);
                    List<String> list = hashOps.multiGet(range);

                    List<SeckillRedisVo> collect = list.stream().map(s1 -> {
                        SeckillRedisVo seckillRedisVo = JSON.parseObject(s1, SeckillRedisVo.class);
                        return seckillRedisVo;
                    }).collect(Collectors.toList());

                    return collect;
                }
            }
        }
        return null;
    }

    @Override
    public SeckillRedisVo getSeckillWithSkuid(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_SESSION_RELATION);
        if(hashOps!=null){
            Set<String> keys = hashOps.keys();
            if(keys!=null && keys.size()>0){
                String reg = "\\d_"+skuId;
                for (String key : keys) {
                    if (key.matches(reg)) {
                        String s = hashOps.get(key);
                        SeckillRedisVo seckillRedisVo = JSON.parseObject(s, SeckillRedisVo.class);
                        long currentTimeMillis = System.currentTimeMillis();
                        Long startTime = seckillRedisVo.getStartTime();
                        Long endTime = seckillRedisVo.getEndTime();
                        if(currentTimeMillis>startTime && currentTimeMillis<endTime){
                            return seckillRedisVo;
                        }else {
                            seckillRedisVo.setRandomCode(null);
                            return seckillRedisVo;
                        }
                    }
                }
            }else {
                return null;
            }

        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SECKILL_SESSION_RELATION);
        String value = hashOps.get(killId);
        SeckillRedisVo seckillRedisVo = JSON.parseObject(value, SeckillRedisVo.class);
        if(seckillRedisVo!=null){
            //判断这个人是否购买过
            //原子性操作
            MemberEntity memberEntity = SeckillInterceptor.threadLocal.get();
            Long memberEntityId = memberEntity.getId();
            Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(memberEntityId + "_" + killId, "user-lock", seckillRedisVo.getEndTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
            if(aBoolean){
                //没有购买过
                //验证数量是否合法
                int count = seckillRedisVo.getSeckillCount().intValue();
                int limitCount = seckillRedisVo.getSeckillLimit().intValue();
                String randomCode = seckillRedisVo.getRandomCode();
                if(num<count && num<=limitCount){
                    //获取信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_SKU_COUNT_SEMAPHORE + randomCode);
                    boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                    if(b){
                        //获取信号量成功
                        //给订单系统发消息，创建订单
                        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                        String orderSn = IdWorker.getTimeId();
                        seckillOrderTo.setOrderSn(orderSn);
                        seckillOrderTo.setMemberId(memberEntityId);
                        seckillOrderTo.setNum(num);
                        seckillOrderTo.setPromotionSessionId(seckillRedisVo.getPromotionSessionId());
                        seckillOrderTo.setSeckillPrice(seckillRedisVo.getSeckillPrice());
                        seckillOrderTo.setSkuId(seckillRedisVo.getSkuId());
                        rabbitTemplate.convertAndSend("order-event-exchange","seckill.to.order",seckillOrderTo);
                        return orderSn;
                    }
                }
            }
        }
        return null;
    }

    private void upSeckillSessionAndSkuInfo(List<SeckillSessionTo> seckillSessionTos) {
        for (SeckillSessionTo seckillSessionTo : seckillSessionTos) {
            long time = seckillSessionTo.getStartTime().getTime();
            long time1 = seckillSessionTo.getEndTime().getTime();
            String key = SECKILL_SESSION+time+"_"+time1;
            if(!stringRedisTemplate.hasKey(key)){
                List<String> collect = seckillSessionTo.getSeckillSkuRelationEntities().stream().map(seckillSkuRelationTo -> {
                    Long skuId = seckillSkuRelationTo.getSkuId();
                    Long promotionSessionId = seckillSkuRelationTo.getPromotionSessionId();
                    String value = promotionSessionId+"_"+skuId;
                    return value;
                }).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(key,collect);
            }
        }
        log.info("上架场次信息成功");
    }

    private void upSeckillSession(List<SeckillSessionTo> seckillSessionTos) {
        BoundHashOperations<String, String, String> hashOperations = stringRedisTemplate.boundHashOps(SECKILL_SESSION_RELATION);
        seckillSessionTos.forEach(seckillSessionTo -> {
            seckillSessionTo.getSeckillSkuRelationEntities().forEach(seckillSkuRelationTo -> {
                String key = seckillSkuRelationTo.getPromotionSessionId()+"_"+seckillSkuRelationTo.getSkuId();
                if (!hashOperations.hasKey(key)) {
                    SeckillRedisVo seckillRedisVo = new SeckillRedisVo();
                    //查询商品详细信息
                    R info = productFeign.info(seckillSkuRelationTo.getSkuId());
                    if(info.getCode()==0){
                        SkuInfoEntity skuInfoEntity = info.getData("skuInfo", new TypeReference<SkuInfoEntity>() {});
                        seckillRedisVo.setSkuInfoEntity(skuInfoEntity);
                    }
                    //设置相关信息
                    BeanUtils.copyProperties(seckillSkuRelationTo,seckillRedisVo);
                    //设置时间
                    seckillRedisVo.setStartTime(seckillSessionTo.getStartTime().getTime());
                    seckillRedisVo.setEndTime(seckillSessionTo.getEndTime().getTime());
                    //随机码
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    seckillRedisVo.setRandomCode(randomCode);

                    hashOperations.put(key, JSON.toJSONString(seckillRedisVo));

                    //信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SECKILL_SKU_COUNT_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(seckillSkuRelationTo.getSeckillCount().intValue());
                }
            });

        });
        log.info("上架商品信息成功");
    }

}
